<?php

//App::uses('TopClient','TaobaoSDK');
include_once ROOT.DS.'lib'.DS.'TaobaoSDK'.DS.'TopSdk.php';

App::uses('TopUtility', 'Utility');

class TopController extends OauthAppController {

    public $name = 'Top';
    
    public $client = null;

    public $components = array('Cookie','Session', 'Hook'=>array(),
    );

    public $top_oauth = array(); 
    
    public $top_util = null;
    
 	public function beforeFilter()
    {
    	$Oauthbinds = $this->Session->read('Auth.Oauthbind');
    	$this->top_oauth=array();
    	if(!empty($Oauthbinds)){
	    	foreach($Oauthbinds as $oauth){
	    		if($oauth['Oauthbind']['source']=='top'){
	    			$this->top_oauth = $oauth['Oauthbind'];
	    			break;
	    		}
	    	}
    	}
    	if(empty($this->top_oauth) && !in_array($this->action,array('login','loginCallback'))){
			$this->__message(__('need login'),'/',20);
    	}
	print_r($this->top_oauth);
        $this->top_util = new TopUtility(TOP_AKEY,TOP_SKEY,$this->top_oauth['oauth_token']);
    	parent::beforeFilter();
    }


    
    public function login() {
		// $aurl = 'http://container.api.tbsandbox.com/container?encode=utf-8&appkey='.TOP_AKEY;
		$aurl = 'http://container.api.taobao.com/container?encode=utf-8&appkey='.TOP_AKEY;
		header('location:'.$aurl);	
		exit;
    }

    public function addMember(){
        $ret = $this->top_util->addMember('llscity');
    }
    public function getMemberGroup(){
        $ret = $this->top_util->getMemberGroup('tb44277369');
    }


    public function addGroup(){
        $ret = $this->top_util->addGroup('测试分组');
        exit;
    }

    public function tags(){
    	$c = new TopClient;
		$c->appkey = TOP_AKEY;
		$c->secretKey = TOP_SKEY;
		$req = new TmallPromotagTagFindRequest;
		$req->setPageNo(1);
		$req->setPageSize(20);
		$req->setTagName("标签名");
		$req->setTagId(12345);
		$resp = $c->execute($req, $sessionKey);
    }

    public function applyTag(){
    	$c = new TopClient;
		$c->appkey = TOP_AKEY;
		$c->secretKey = TOP_SKEY;
		$req = new TmallPromotagTagApplyRequest;
		$req->setTagName("生日特价人群");
		$req->setTagDesc("这是一个标签描述");
		$req->setStartTime("2014-01-01 00:00:00");
		$req->setEndTime("2014-11-01 00:00:00");
		$resp = $c->execute($req, $sessionKey);
		print_r($resp);
		exit;
    }

    public function setTag($tagid,$nick){
    	$c = new TopClient;
		$c->appkey = TOP_AKEY;
		$c->secretKey = TOP_SKEY;
		$req = new TmallPromotagTaguserSaveRequest;
		$req->setTagId($tagid);
		$req->setNick($nick);
		$resp = $c->execute($req, $sessionKey);
		print_r($resp);
		exit;
    }
    
    /**
     * 基于TOP协议的登录授权方式介绍 
     * http://open.taobao.com/doc/detail.htm?spm=a219a.7386781.0.0.gFsJwz&id=105
     * 回调URL
     * http://www.miaomiaoxuan.com/?top_appkey=12336677&top_parameters=ZXhwaXJlc19pbj04NjQwMCZpZnJhbWU9MSZyMV9leHBpcmVzX2luPTg2NDAwJnIyX2V4cGlyZXNfaW49ODY0MDAmcmVfZXhwaXJlc19pbj0yNTkyMDAwJnJlZnJlc2hfdG9rZW49NjEwMTAxNmU0NmY2N2IwMTczNmIwOGI0MTJmMTQ3ZTgyZmVmNjVkZjM5N2FmYTIxOTIzMzkwODQmdHM9MTQwNzU5Nzk2OTUyMyZ2aXNpdG9yX2lkPTE5MjMzOTA4NCZ2aXNpdG9yX25pY2s9aWRlYW11c3RlciZ3MV9leHBpcmVzX2luPTg2NDAwJncyX2V4cGlyZXNfaW49ODY0MDA%3D&top_session=6100c161ff32a9c1566f55c716bfad990d1cd4bca550fe5192339084&agreement=true&agreementsign=12336677-23459965-192339084-0D79D1BBC0DFFC29FD5874A859F730ED&top_sign=Mrg2%2FqhiDxSbhMPXAjXpdw%3D%3D
     * top_parameters是插件容器传递给插件的参数集合，具体的参数内容见：
     * http://open.taobao.com/doc/detail.htm?spm=a219a.7386781.0.0.P8lpeu&id=110
     * 基于TOP协议的登录返回参数校验 
     * top_parameters具体的产生方式是：base64(key1=value1&key2=value2……；
     **/
    public function loginCallback()
    {
    	if(isset($_REQUEST['top_appkey']) && isset($_REQUEST['top_parameters']) && isset($_REQUEST['top_session']) && isset($_REQUEST['agreement']) 
            && isset($_REQUEST['agreementsign']) && isset($_REQUEST['top_sign']) )
        {
            //从淘宝TOP登录返回的回调参数
            //base64(md5(top_appkey+top_parameters+top_session+app_secret))

            //echo base64_encode(md5($_REQUEST['top_appkey'].$_REQUEST['top_parameters'].$_REQUEST['top_session'].TOP_SKEY));
            
            // if($_REQUEST['top_sign'] == base64_encode(md5($_REQUEST['top_appkey'].$_REQUEST['top_parameters'].
            //     $_REQUEST['top_session'].TOP_SKEY))) 
            { //验证参数是否合法

                parse_str(base64_decode($_REQUEST['top_parameters']),$parameters);

        		$params = array();
        		$params['appkey'] = TOP_AKEY;
        		$params['refresh_token'] = $parameters['refresh_token'];
        		$params['sessionkey'] = $_REQUEST['top_session'];
		        $sign = $this->sign($params);
		
		        $refresh_url = 'http://container.open.taobao.com/container/refresh?'.http_build_query($params).'&sign='.$sign;
                App::uses('CrawlUtility', 'Utility');
        		$refresh_ret = CrawlUtility::getRomoteUrlContent($refresh_url);
        		$refresh_json = json_decode($refresh_ret,true);
        		print_r($refresh_json);

                $auth_info = array();
                $auth_info['type'] = 'top';
                $auth_info['access_token'] = $refresh_json['top_session'];
                $auth_info['oauth_user_id'] = $parameters['visitor_id'];
                $auth_info['oauth_user_nick'] = $parameters['visitor_nick'];
                $auth_info['refresh_token'] = $refresh_json['refresh_token'];
                $auth_info['oauth_expires'] = $refresh_json['expires_in'];
                $auth_info['oauth_timestamp'] = intval($parameters['ts']/1000); //毫秒换算成秒

                print_r($auth_info);
                App::uses('OauthUtility', 'Utility');
                $ret = OauthUtility::new_oauth($auth_info);
                $this->Session->write('Auth.User',$ret['User']);
                $this->Cookie->write('Auth.User',$ret['User'],true,2592000);
                $this->Session->write('Auth.Oauthbind',$ret['Oauthbinds']);
            }
        }
    }
    private function sign($params = array())
    {
    	ksort($params);
    	$str = '';
    	foreach($params as $key => $val)
    	{
    		$str .= $key.$val;
    	}
    	$str .= TOP_SKEY;
    	$str = strtoupper(md5($str));
    	return $str;
    }

	
}
?>
